// merchants/addCoupon/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    gradeid: 0, //股东等级id
    allianceid: 0,
    flyerid: 0,//传单活动ID
    showSendmodel: false, //0折叠，1展开
    type: 0, //0赠品券；1满减券
    coupontypeid: 0,
    nowData: '',
    nowtime: '',
    couponTypeName: '',
    money: 0,
    count: 0,
    sendModel: 0,
    getModel: 0, //领取方式
    useModel: 0, //0可叠加，1不可叠加
    orderAmountLower: 0,
    useTimeType: 1, //0绝对时间，1相对时间
    useExpireTime: 30, //几天后失效
    sendStartDate: '', //发券日期
    sendStartTime: '',
    sendEndDate: '',
    sendEndTime: '',
    useStartDate: '', //使用日期
    useStartTime: '',
    useEndDate: '',
    useEndTime: '',
    remark: '',
    extCode1: '',
    extCode2: '',
    detailpics: [],
    isEditor: 0,
    isWxStore: false,//是否开通微信商户
    isWxCard: 0,//0普通卡券，1微信卡券, 2 支付宝券
    coverImg: '',//微信卡券封面图
    isalliance: 0,//是否联盟券
    clickTime: 0,
    expireMsgTips: ''//到期短信提醒
  },

  // 新增优惠券
  saveCounpon: function () {
    let that = this;
    let isPackage = 0;
    let getCount = 1;
    let count = that.data.count;
    let orderAmountLower = that.data.orderAmountLower;
    let isWxCard = that.data.isWxCard;
    let detailpics = that.data.detailpics;
    let gradeid = that.data.gradeid;
    let useStartTime = '1970-01-01';
    let useEndTime = '1970-01-01';
    let sendStartTime = that.data.sendStartDate + " " + that.data.sendStartTime;
    let sendEndTime = that.data.sendEndDate + " " + that.data.sendEndTime;

    if (that.data.flyerid > 0) {
      gradeid = that.data.flyerid;
    }
    if (detailpics.length > 0) {
      for (var i = 0; i < detailpics.length; i++) {
        var Index = detailpics[i].lastIndexOf('l/');
        detailpics[i] = detailpics[i].substr(Index + 2, detailpics[i].length);
      }
    }
    detailpics = detailpics.toString();

    let picPath = that.data.coverImg;
    if (picPath) {
      var strlen = picPath.lastIndexOf('l/');
      picPath = picPath.substr(strlen + 2, picPath.length);
    }

    if (that.data.type == 1) {      
      if (!orderAmountLower || orderAmountLower <= 0) {
        that.checkWrite('请输入大于0的最小订单金额'); return
      }
      if (!that.data.money || that.data.money <= 0) {
        that.checkWrite('请输入大于0的减免金额'); return
      }
      if (parseInt(that.data.money) > parseInt(orderAmountLower)) {
        that.checkWrite('减免金额不能大于最小订单金额')
        return
      }
    }
    //赠品券不能同步微信isWxCard=0
    if (!that.data.type) {
      isWxCard = 0;
      if (!that.data.couponTypeName) {
        that.checkWrite('请输入赠品券名称'); return
      }
      if (orderAmountLower < 0) {
        that.checkWrite('请输入大于0的赠品券价值'); return
      }
      if (!orderAmountLower) {//赠品券价值
        orderAmountLower = 0
      }
    }

    // 相对时间
    if (that.data.useTimeType == 1) {
      if (that.data.useExpireTime == "") {
        that.checkWrite('请选择有效天数'); return
      }
    }
    //股东优惠券/传单礼包优惠券
    if (that.data.gradeid > 0 || that.data.flyerid > 0) {
      isPackage = 1;
    }
    //联盟优惠券/股东优惠券/传单礼包优惠券
    if (that.data.allianceid > 0 || that.data.gradeid > 0 || that.data.flyerid > 0) {
      if (count != "") {
        getCount = count;
      }
      count = 0;
    } else {
      //普通优惠券
      if (count == "") {
        count = 0;
      }
      if (count > 1000000) {
        that.checkWrite('请输入小于1000000的数量'); return
      }
    }
 
    //发放时间判断
    if (sendStartTime > sendEndTime) {
      that.checkWrite('发放开始时间不能大于发放结束时间'); return
    }
 
    if(isWxCard > 0 && that.getInervalDay(sendStartTime,sendEndTime)>90){
      that.checkWrite('券发放时间不超过90天'); return;
    }

    // 使用时间判断
    if (that.data.useTimeType == 0) {//绝对时间
      that.data.useExpireTime = 0;
      useStartTime = that.data.useStartDate + " " + that.data.useStartTime;
      useEndTime = that.data.useEndDate + " " + that.data.useEndTime;
      if (!useStartTime || !useEndTime) {
        that.checkWrite('请输入使用时间段'); return;
      }
      if (useStartTime > useEndTime) {
        that.checkWrite('使用开始时间不能大于使用结束时间'); return;
      }
      if(isWxCard > 0 && that.getInervalDay(useStartTime,useEndTime)>90){
        that.checkWrite('券使用时间不能超过90天'); return;
      }
    }
    let data = {
      CreateUid: app.globalData.userInfo.Uid,
      CouponTypeName: that.data.couponTypeName,
      Money: parseInt(that.data.money),
      Count: parseInt(count),//优惠券总数量
      GetCount: parseInt(getCount),//单人领取优惠券数量
      SendModel: parseInt(that.data.sendModel), //发放方式(0代表免费领取,1代表手动发放,2代表随活动发放) ,
      GetModel: parseInt(that.data.getModel), //领取方式(当且仅当发放方式为免费领取时有效.0代表无限制,1代表限领一张,2代表每天限领一张) ,
      UseModel: parseInt(that.data.useModel), // 使用方式(0代表可以叠加,1代表不可以叠加) ,
      OrderAmountLower: parseInt(orderAmountLower), //最小订单金额
      SendStartTime: sendStartTime,
      SendEndTime: sendEndTime,
      UseTimeType: parseInt(that.data.useTimeType), // 使用时间类型0:绝对时间，1：相对时间 ,
      UseExpireTime: that.data.useExpireTime, //使用过期时间 ,
      UseStartTime: useStartTime,
      UseEndTime: useEndTime,
      State: 1,
      ExtCode1: that.data.extCode1, //扩展字段1买什么,
      ExtCode2: that.data.extCode2, //扩展字段2送什么 ,
      Remark: that.data.remark,
      DetailPics: detailpics,
      isPackage: isPackage,
      gradeId: gradeid,//股东等级id/传单活动id
      Logo: picPath,
      AllianceId: that.data.allianceid,//联盟id
      RemindDay: that.data.expireMsgTips == '' ? 7 : that.data.expireMsgTips,
      Type: isWxCard
    };
    
    wx.showLoading({title: '提交中',mask: true})
    wx.request({
      url: app.globalData.host + '/api/Coupon/AddCouponType',
      data: data,
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          wx.showToast({
            title: '添加成功',
            duration: 2000,
          })
          if (that.data.allianceid > 0) {//联盟券
            wx.redirectTo({
              url: '/merchant/alliance/allianceManager/index?tagindex=3'
            })
          } else if (that.data.gradeid > 0) {//股东礼包券
            wx.redirectTo({
              url: '/merchant/share/holderCoupon/index?typeofCard=1&gradeid=' + that.data.gradeid
            })
          } else if (that.data.flyerid > 0) {//传单礼包优惠券
            wx.redirectTo({
              url: '/merchant/flyer/flyerCardAndCoupon/index?typeofCard=1&flyerid=' + that.data.flyerid
            })
          } else {//普通商家券
            wx.redirectTo({
              url: '/merchant/merchants/manager/index?typeofCard=1'
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  showTips: function (e) {
    let count = this.data.clickTime;
    if (count == 0 && e.detail.value > 10) {
      wx.showModal({
        title: '提示',
        content: '此数量是一个客户领取的数量，建议不超过10，如果一个客户只发1张，则此数量应该填写 1',
        showCancel: false,
      })
      this.setData({
        clickTime: count + 1
      })
    }
  },
  /**
   * 上传详细图片
   */

  uploadDetailImage: function (e) { //这里是选取图片的方法
    var that = this;
    var detailPics = [];
    detailPics = that.data.detailpics
    var pics = [];
    if (detailPics.length >= 6) {
      wx.showToast({
        title: '最多选择6张！',
      })
      return;
    }
    wx.chooseImage({
      count: 6, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var imgs = res.tempFilePaths;
        for (var i = 0; i < imgs.length; i++) {
          pics.push(imgs[i])
        }
        that.uploadimgs({
          url: app.globalData.host + '/api/tool/upload?operation=uploadcouponimage', //这里是你图片上传的接口
          path: pics, //这里是选取的图片的地址数组
        });
      },
    })
  },
  // 上传微信卡券封面图
  uploadCoverImage: function () {
    var that = this;
    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var imgs = res.tempFilePaths;
        that.uploadimg({
          url: app.globalData.host + '/api/tool/upload?operation=uploadcouponimage', //这里是你图片上传的接口
          path: imgs, //这里是选取的图片的地址数组
        });
      },
    })
  },

  // 单图上传
  uploadimg: function (data) {
    wx.showLoading({
      title: '提交中...',
      mask: true,
    })
    var that = this;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[0],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        var str = resp.data
        var pic = JSON.parse(str);
        var coverImg = 'https://static.711688.net.cn/upload/coupondetail/' + pic.Data;
        that.setData({
          coverImg: coverImg
        })
      },
      fail: (res) => {
        console.log('fail:');
      },
    });
  },

  //多张图片上传
  uploadimgs: function (data) {
    wx.showLoading({
      title: '提交中...',
      mask: true,
    })
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        success++;
        var str = resp.data
        var pic = JSON.parse(str);
        var pic_name = 'https://static.711688.net.cn/upload/coupondetail/' + pic.Data;
        var detailpics = that.data.detailpics;
        detailpics.push(pic_name);
        that.setData({
          detailpics: detailpics
        })
      },
      fail: (res) => {
        fail++;
      },
      complete: () => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用     
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimgs(data);
        }
      }
    });
  },
  //商品详情图片预览
  preViewDetailsImg: function (e) {
    let list = this.data.detailpics;
    let src = e.currentTarget.dataset.src;
    let imgs = [];
    for (let i = 0; i < list.length; i++) {
      imgs.push(list[i]);
    }
    imgs.join(",");
    wx.previewImage({
      current: src,
      urls: imgs,
    })
  },

  /**
   * 长按删除详细图片
   */
  deleteDetailPic: function (e) {
    var that = this;
    var newPics = that.data.detailpics;
    newPics.splice(e.currentTarget.dataset.index, 1);
    that.setData({
      detailpics: newPics
    })
  },

  // 优惠券详情
  getCouponDetail: function (coupontypeid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCouponTypeInfo?couponTypeId=' + coupontypeid,
      success: function (res) {
        let couponType = res.data.Data;
        let count = couponType.Count;
        let isWxCard = couponType.Type;
        let detailpics = couponType.DetailPics;
        let imgDomain = 'https://static.711688.net.cn/upload/coupondetail/';
        let coverImg = couponType.Logo ? imgDomain + couponType.Logo : '';
        let list = [];
        if (detailpics != '') {
          var newDetailPics = detailpics.split(",");
          for (let i = 0; i < newDetailPics.length; i++) {
            list[i] = imgDomain + newDetailPics[i];
          }
        }
        
        if (that.data.isalliance == 1 || that.data.gradeid > 0 || that.data.flyerid > 0) {
          count = couponType.GetCount;
        }        

        that.setData({
          couponTypeName: couponType.CouponTypeName,
          money: couponType.Money,
          count: count,
          sendModel: couponType.SendModel,
          getModel: couponType.GetModel,
          useModel: couponType.UseModel,
          orderAmountLower: couponType.OrderAmountLower,
          useTimeType: couponType.UseExpireTime > 0 ? 1 : 0,
          useExpireTime: couponType.UseExpireTime, //几天后失效
          sendStartDate: couponType.SendStartTime.substr(0, 10), //发券日期
          sendStartTime: couponType.SendStartTime.substr(11, 8),
          sendEndDate: couponType.SendEndTime.substr(0, 10),
          sendEndTime: couponType.SendEndTime.substr(11, 8),
          useStartDate: couponType.UseStartTime.substr(0, 10), //使用日期
          useStartTime: couponType.UseStartTime.substr(11, 8),
          useEndDate: couponType.UseEndTime.substr(0, 10),
          useEndTime: couponType.UseEndTime.substr(11, 8),
          remark: couponType.Remark,
          extCode1: couponType.ExtCode1,
          extCode2: couponType.ExtCode2,
          detailpics: list,
          isWxCard: isWxCard,
          coverImg: coverImg,
          expireMsgTips: couponType.RemindDay
        })
      }
    })
  },
  //填写判断
  checkWrite: function (str) {
    wx.showModal({
      title: '提示',
      content: str,
      showCancel: false
    })
  },
  addDate: function (dataStr, dayCount) {
    var strdate = dataStr; //日期字符串
    var isdate = new Date(strdate.replace(/-/g, "/")); //把日期字符串转换成日期格式
    //日期加1天
    isdate = new Date((isdate / 1000 + (86400 * dayCount)) * 1000);
    var pdate = isdate.getFullYear() + "-" + (isdate.getMonth() + 1) + "-" + (isdate.getDate());
    return pdate;
  },
  // 两个日期相差的天数（传入的时间为标准时间格式）
  getInervalDay: function (startDate, endDate) {
    var startDate = new Date(startDate.replace(/-/g, "/"));; //日期字符串
    var endDate = new Date(endDate.replace(/-/g, "/"));; //日期字符串
    var ms = endDate.getTime() - startDate.getTime();
    var day = ms / 1000 / 60 / 60 / 24;
    return day;
  },


  showSendModel: function () {
    this.setData({
      showSendmodel: !this.data.showSendmodel
    })
  },

  //获取微信商户
  getWxStore: function () {
    let that = this;
    that.CurentTime();
    that.CurentData();
    let sendStartTime = that.data.sendStartDate + that.data.sendStartTime;
    let sendEndDate = that.addDate(sendStartTime, 365);
    let month = '';
    let date = '';
    let newsendEndDate11 = '';
    wx.request({
      url: app.globalData.host + '/api/WxStore/GetWxStoreByUid?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Data) {
          that.data.isWxStore = true;
          if (that.data.type == 1) {
            sendEndDate = that.addDate(sendStartTime, 90);
          }
          that.setData({
            isWxCard: 1
          })
        }
        let newsendendDate = sendEndDate.split("-");
        if (newsendendDate[1] < 10) {
          month = '0' + newsendendDate[1]
        } else {
          month = newsendendDate[1]
        }
        if (newsendendDate[2] < 10) {
          date = '0' + newsendendDate[2]
        } else {
          date = newsendendDate[2]
        }
        newsendEndDate11 = newsendendDate[0] + '-' + month + '-' + date;
        that.setData({
          sendEndDate: newsendEndDate11,
          useEndDate: newsendEndDate11
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getWxStore();
    if (options.type == 1) { //满减
      wx.setNavigationBarTitle({
        title: '新建优惠券'
      })
      this.setData({
        type: options.type
      })
    }
    if (options.type == 0) { //赠品券
      let getModel = 1;
      if (options.gradeid > 0 || options.allianceid > 0 || options.flyerid > 0) {
        getModel = 0;
      }
      wx.setNavigationBarTitle({
        title: '新建赠品券'
      })
      this.setData({
        getModel: getModel
      })
    }
    if (options.coupontypeid) {
      this.getCouponDetail(options.coupontypeid);
      this.setData({
        coupontypeid: options.coupontypeid
      })
    }
    if (options.isEditor) {
      this.setData({
        isEditor: options.isEditor
      })
    }
    if (options.isalliance) {
      this.setData({
        isalliance: options.isalliance
      })
    }
    if (options.gradeid > 0) {
      this.setData({
        gradeid: options.gradeid
      })
    }
    if (options.allianceid > 0) {
      this.setData({
        allianceid: options.allianceid
      })
    }
    if (options.flyerid > 0) {
      this.setData({
        flyerid: options.flyerid
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  bindCouponTypeName: function (e) {
    this.setData({
      couponTypeName: e.detail.value
    })
  },

  //赠品券价值/满xx
  bindAmountLower: function (e) {
    this.setData({
      orderAmountLower: e.detail.value
    })
  },
  bindMoney: function (e) {
    this.setData({
      money: e.detail.value
    })
  },
  bindCount: function (e) {
    this.setData({
      count: e.detail.value
    })
  },
  bindDays: function (e) {
    this.setData({
      useExpireTime: e.detail.value
    })
  },
  bindDescVal: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },
  bindExtcode1: function (e) {
    this.setData({
      extCode1: e.detail.value
    })
  },
  bindExtcode2: function (e) {
    this.setData({
      extCode2: e.detail.value
    })
  },
  modelUpdate: function (e) {
    if (e.currentTarget.dataset.sendmodel) {
      this.setData({
        sendModel: e.currentTarget.dataset.sendmodel
      })
    }
    if (e.currentTarget.dataset.getmodel) {
      this.setData({
        getModel: e.currentTarget.dataset.getmodel
      })
    }
    if (e.currentTarget.dataset.usemodel) {
      this.setData({
        useModel: e.currentTarget.dataset.usemodel
      })
    }
    if (e.currentTarget.dataset.usetimetype) {
      this.setData({
        useTimeType: e.currentTarget.dataset.usetimetype
      })
    }
    if (e.currentTarget.dataset.iswxcard) {
      this.setData({
        isWxCard: e.currentTarget.dataset.iswxcard
      })
    }
  },

  // 获取当前年月
  CurentData: function () {
    var that = this;
    var now = new Date();
    var year = now.getFullYear(); //年
    var month = now.getMonth() + 1; //月
    var day = now.getDate(); //日
    var clock = year + "-";
    if (month < 10)
      clock += "0";
    clock += month + "-";
    if (day < 10)
      clock += "0";
    clock += day + " ";
    that.setData({
      nowData: clock,
      sendStartDate: clock,
      useStartDate: clock,
    })
  },
  // 获取当前时间分秒
  CurentTime: function () {
    var that = this;
    var now = new Date();
    var hh = now.getHours(); //时
    var mm = now.getMinutes(); //分
    var ss = now.getSeconds() //秒
    var clock = "";
    if (hh < 10)
      clock += "0";
    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm + ":";
    if (ss < 10) clock += '0';
    clock += ss;
    that.setData({
      nowtime: clock,
      sendStartTime: clock,
      sendEndTime: clock,
      useStartTime: clock,
      useEndTime: clock
    })
  },
  //日期
  bindDateChange: function (e) {
    var date = e.detail.value;
    this.setData({
      sendStartDate: date
    })
  },
  //bindTimeChange时间
  bindTimeChange: function (e) {
    var time = e.detail.value + ":00";
    this.setData({
      sendStartTime: time
    })
  },
  //日期
  bindDateChange1: function (e) {
    var date = e.detail.value;
    this.setData({
      sendEndDate: date
    })
  },
  //bindTimeChange时间
  bindTimeChange1: function (e) {
    var time = e.detail.value + ":00";
    this.setData({
      sendEndTime: time
    })
  },
  //日期
  bindDateChange2: function (e) {
    var date = e.detail.value;
    this.setData({
      useStartDate: date
    })
  },
  //bindTimeChange时间
  bindTimeChange2: function (e) {
    var time = e.detail.value + ":00";
    this.setData({
      useStartTime: time
    })
  },
  //日期
  bindDateChange3: function (e) {
    var date = e.detail.value;
    this.setData({
      useEndDate: date
    })
  },
  //bindTimeChange时间
  bindTimeChange3: function (e) {
    var time = e.detail.value + ":00";
    this.setData({
      useEndTime: time
    })
  },
  bindExpireMsg: function(e){
    var days = e.detail.value;
    this.setData({
      expireMsgTips: days
    })
  }
})